package lin.j4fun.mongo;

import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import lin.j4fun.utility.MessagePrinter;

import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class DBConnector {

	private String host;
	private String database;
	private int port;
	private MongoClient mongoClient;
	private static Logger log;

	private static DBConnector uniqueInstance = new DBConnector();

	private DBConnector() {
	}

	public static DBConnector getInstance() {
		log = Logger.getLogger(DBConnector.class);
		return uniqueInstance;

	}

	public void connect(String host, int port, String database) {
		this.host = host;
		this.port = port;
		this.database = database;

		connect();
	}

	public void connect() {
		try {
			if (this.host.isEmpty()) {
				this.host = "127.0.0.1";
				this.port = 27017;
			}
			doConnect();
			log.info("DB Connected...");
		} catch (UnknownHostException e) {
			log.error(e.getMessage());
		}
	}

	private void doConnect() throws UnknownHostException {
		ServerAddress sa = new ServerAddress(host, port);
		mongoClient = new MongoClient(sa);
	}
}
